package cn.com.pansky.action.bank;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import net.vsame.url2sql.action.CommonAction;
import net.vsame.url2sql.helper.SqlHelper;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.StringUtils;

import cn.com.pansky.payment.PayConf;
import cn.com.pansky.util.AppUtils;
import cn.com.pansky.util.DateUtil;
import cn.com.pansky.util.EncryptionUtils;
import cn.com.pansky.util.HttpClientUtil;
import cn.com.pansky.util.PropertiesUtil;

import com.abc.pay.client.JSON;
import com.abc.pay.client.ebus.RefundRequest;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.psbc.payment.client.SignatureService;

/**
 * 银行退货交易
 * @author Administrator
 *
 */
public class BankRefundAction extends CommonAction{
	
	/**
	 * 银行退货操作
	 */
	public void bankRefund() {
		System.out.println("------退货交易开始------");
		JSONObject object = new JSONObject();
		object.put("AAZ295", context.getParam("AAZ295")); // 支付类别
		object.put("AAZ288", context.getParam("AAZ288")); // 订单号
		object.put("AAD017", context.getParam("AAD017")); // 交易日期
		object.put("AAD008", context.getParam("AAD008")); // 平台交易流水号
		object.put("AAE019", context.getParam("AAE019")); // 交易金额
		object.put("AAE051", context.getParam("AAE051")); // 商户号
		object.put("AAZ2881", context.getParam("AAZ2881")); // 邮储支付订单号
		object.put("BAE300", context.getParam("BAE300")); // 秘钥
		System.out.println("退货订单信息："+object.toString());
		String bankType = object.getString("AAZ295"); // 银行类别
		if("YC".equals(bankType) || "315".equals(bankType)) {
			System.out.println("------邮储退货交易开始--------");
			psbcRefund(object); // 邮储退货
			System.out.println("------邮储退货交易结束--------");
		} else if(bankType.equals("NH") || "103".equals(bankType)) {
			System.out.println("------农行退货交易开始--------");
			abcRefund(object); // 农行退货
			System.out.println("------农行退货交易结束--------");
		} else if(bankType.equals("JH") || "105".equals(bankType)) {
			System.out.println("------建行退货交易开始--------");
			jhRefund(object); // 建行退货
			System.out.println("------建行退货交易结束--------");
		} else if(bankType.equals("WX")) {
			System.out.println("------微信退货交易开始--------");
			wxRefund(object); // 微信退货
			System.out.println("------微信退货交易结束--------");
		}
		System.out.println("-------------退货交易结束----------------");
	}
	
	public void wxRefund(JSONObject object) {
		//<xml>
		//   <appid>wx2421b1c4370ec43b</appid>
		//   <mch_id>10000100</mch_id>
		//   <nonce_str>6cefdb308e1e2e8aabd48cf79e546a02</nonce_str>
		//   <op_user_id>10000100</op_user_id>
		//   <out_refund_no>1415701182</out_refund_no>
		//   <out_trade_no>1415757673</out_trade_no>
		//   <refund_fee>1</refund_fee>
		//   <total_fee>1</total_fee>
		//   <transaction_id></transaction_id>
		//   <sign>FE56DD4AA85C0EECA82C35595A69E153</sign>
		//</xml>
		try {
			URL url = new URL("https://api.mch.weixin.qq.com/secapi/pay/refund");
	        URLConnection con = url.openConnection();
	        con.setDoOutput(true);
	        con.setRequestProperty("Pragma:", "no-cache");
	        con.setRequestProperty("Cache-Control", "no-cache");
	        con.setRequestProperty("Content-Type", "text/xml");
	
	        OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());    
	        Map<String, String[]> paramsMap = new HashMap<String, String[]>();
	        StringBuilder sb = new StringBuilder();
	        sb.append("<xml>");
	        sb.append("    <appid>"+object.getString("appid")+"</appid>");		//应用ID
	        paramsMap.put("appid", new String[] { object.getString("appid") });
	        sb.append("    <mch_id>"+object.getString("AAE051")+"</mch_id>");				//商户号
	        paramsMap.put("mch_id", new String[] { object.getString("AAE051") });
	        sb.append("    <nonce_str>C380BEC2BFD727A4B6845133519F3AD6</nonce_str>");			//随机字符串
	        paramsMap.put("nonce_str", new String[] { "C380BEC2BFD727A4B6845133519F3AD6" });
	        sb.append("    <out_trade_no>"+object.getString("AAZ288")+"</out_trade_no>");			//商户订单号
	        paramsMap.put("out_trade_no", new String[] { object.getString("AAZ288") });
	        sb.append("    <out_refund_no>"+object.getString("AAZ288")+"</out_refund_no>");			//商户退款单号
	        paramsMap.put("out_refund_no", new String[] { object.getString("AAZ288") });
	        sb.append("    <total_fee>"+object.getString("AAE019")+"</total_fee>");			//总金额
	        paramsMap.put("total_fee", new String[] { object.getString("AAE019") });
	        sb.append("    <refund_fee>"+object.getString("AAE019")+"</refund_fee>");			//退款金额
	        paramsMap.put("refund_fee", new String[] { object.getString("AAE019") });
	        sb.append("    <op_user_id>"+object.getString("AAE051")+"</op_user_id>");				//操作员
	        paramsMap.put("op_user_id", new String[] { object.getString("AAE051") });
	        String sign = EncryptionUtils.makeSignature(paramsMap, "pansky");
	        sb.append("    <sign>"+sign+"</sign>");		//签名
	        sb.append("</xml>");
	        String xmlInfo = sb.toString();
	        out.write(new String(xmlInfo.getBytes("ISO-8859-1")));
	        out.flush();
	        out.close();
	        BufferedReader br = new BufferedReader(new InputStreamReader(con
	                .getInputStream()));
	        String line = "";
	        String result = "";
	        for (line = br.readLine(); line != null; line = br.readLine()) {
	            result = result + line;
	        }
	        System.out.println(result);
	        String return_code = result.split("<return_code>")[1].split("</return_code>")[0];
	        boolean boo = return_code.contains("SUCCESS");
	        if (boo) {
	        	//TODO 退款申请成功
	        	
			} else {
				//TODO 退款申请失败
				System.out.println(result);
			}
		} catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
	
	/**
	 * 邮储退货交易IPSR
	 */
	public void psbcRefund(JSONObject object) {
		String transName = "IPSR"; // 交易名称
		// 交易数据明文数据封装开始
		String TranAbbr = "IPSR"; // 交易缩写   必填
		String MercDtTm = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); // 商户日期时间 必填
		String TermSsn = object.getString("AAZ288")+DateUtil.current7Time()+"R"; //订单号 必填
		String OSttDate = object.getString("AAD017"); // 原交易商户日期 必填
		String OAcqSsn = object.getString("AAZ2881"); // 原交易订单号 必填
		String MercCode = object.getString("AAE051"); // 商户号 必填  测试数据：1100529310001000003
		String TermCode = ""; // 终端号
		String TranAmt = object.getString("AAE019"); // 交易金额 必填
		String MercUrl = ""; // 商户通知地址
		String Remark1 = ""; // 备注1
		String Remark2 = ""; // 备注2
		
		// 交易数据明文数据封装结束
		// 交易数据明文
		@SuppressWarnings("deprecation")
		String Plain = "TranAbbr="+TranAbbr+"|MercDtTm="+MercDtTm+"|TermSsn="+TermSsn+"|OSttDate="
				+OSttDate+"|OAcqSsn="+OAcqSsn+"|MercCode="+MercCode+"|TermCode="+TermCode
				+"|TranAmt="+TranAmt+"|MercUrl="+URLEncoder.encode(MercUrl)+"|Remark1="+Remark1+"|Remark2="
				+Remark2;
		
		// 交易数据明文签名
		String Signature = SignatureService.sign(Plain);
		String resultStr= "";//要返回的response信息
		HttpClient httpClient = new HttpClient();
		PostMethod postMethod = new PostMethod(PayConf.PayUrl);
		//填入各个表单域的值
		NameValuePair[] data = {
			new NameValuePair("transName", transName),
			new NameValuePair("Plain", Plain),
			new NameValuePair("Signature", Signature),
		};
		// 将表单的值放入postMethod中
		postMethod.setRequestBody(data);
		// 执行postMethod
		int statusCode = 0;
		try {
			statusCode = httpClient.executeMethod(postMethod);
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// HttpClient对于要求接受后继服务的请求，象POST和PUT等不能自动处理转发
		// 301或者302
		if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {  
			// 从头中取出转向的地址
			Header locationHeader = postMethod.getResponseHeader("location");
			@SuppressWarnings("unused")
			String location = null;
			if (locationHeader != null) {
				location = locationHeader.getValue();
			}
		} else {
			try {
				resultStr= postMethod.getResponseBodyAsString();
			} catch (IOException e) {
				e.printStackTrace();
			}
			postMethod.releaseConnection();
		}
		System.out.println("邮储退货返回："+resultStr);
		if(resultStr.indexOf("<ErrorMsg>") != -1) {
			//updOrderAAE356(object, false);
			datas.put("AAE014", "");	//清算日期
			datas.put("AAE015", "");	//支付平台流水
			datas.put("AAE016", TranAbbr);	//交易缩写
			datas.put("AAE017", "");	//商户日期时间
			datas.put("AAE356","2");
			datas.put("AAE013", "失败");
			context.getDatas().put("MSG", datas);
		} else {
			// 返回明文
			String plan = resultStr.substring(resultStr.indexOf("<Plain>")+7, resultStr.indexOf("</Plain>"));
			// 签名
			String Signature1 = resultStr.substring(resultStr.indexOf("<Signature>")+11, resultStr.indexOf("</Signature>"));
			// 验证签名
			boolean validate = SignatureService.verify(plan, Signature1);
			if(validate) {
				plan = plan.replace("|", ",");
				String[] array = plan.split(",");
				String AAE015 = "";
				System.out.println("邮储退货解析完的数组："+array.toString());
				for(int i = 0; i < array.length; i++) {
					String[] keys = array[i].split("=");
					// 响应码RespCode=00000000标识成功
					
					if(keys[0] != null && keys[0].equals("RespCode")) {
						if(keys[1].equals("00000000")) {
							
							for(int j = 0; j < array.length; j++) {
								String[] keyss = array[j].split("=");
								if(keyss[0] != null && keyss[0].equals("AcqSsn")) {
									AAE015 = keyss[1];//支付平台流水
									break;
								} else {
									continue;
								}
							}
							
							datas.put("AAE014", "");	//清算日期
							datas.put("AAE015", AAE015);	//支付平台流水
							datas.put("AAE016", TranAbbr);	//交易缩写
							datas.put("AAE017", "");	//商户日期时间
							datas.put("AAE356","1");
							datas.put("AAE013", "");
							System.out.println("退款成功，返回核心："+datas);
							context.getDatas().put("MSG", datas);
							return;
						} else {
//							updOrderAAE356(object, false);
							datas.put("AAE014", "");	//清算日期
							datas.put("AAE015", "");	//支付平台流水
							datas.put("AAE016", TranAbbr);	//交易缩写
							datas.put("AAE017", "");	//商户日期时间
							datas.put("AAE356","2");
							datas.put("AAE013", keys[2]);
							context.getDatas().put("MSG", datas);
							return;
						}
					}
				}
			} else {
				System.out.println("邮储退货：验证签名失败");
//				updOrderAAE356(object, false);
				datas.put("AAE014", "");	//清算日期
				datas.put("AAE015", "");	//支付平台流水
				datas.put("AAE016", TranAbbr);	//交易缩写
				datas.put("AAE017", "");	//商户日期时间
				datas.put("AAE356","2");
				datas.put("AAE013", "验证签名失败");
				context.getDatas().put("MSG", datas);
			}
		}
	}
	
	/**
	 * 农行退款
	 */
	public void abcRefund(JSONObject object) {
		RefundRequest tRequest = new RefundRequest();
		tRequest.dicRequest.put("OrderDate", new SimpleDateFormat("yyyy/MM/dd").format(new Date()));  //订单日期（必要信息）
		tRequest.dicRequest.put("OrderTime", new SimpleDateFormat("hh:mm:ss").format(new Date())); //订单时间（必要信息）
		tRequest.dicRequest.put("MerRefundAccountNo", "");  //商户退款账号
		tRequest.dicRequest.put("MerRefundAccountName", ""); //商户退款名
		tRequest.dicRequest.put("OrderNo", object.getString("AAZ288")); //原交易编号（必要信息）
		tRequest.dicRequest.put("NewOrderNo", object.getString("AAZ288")+"R"); //交易编号（必要信息）
		tRequest.dicRequest.put("CurrencyCode", PayConf.ORDERCURRENCY); //交易币种（必要信息）
		tRequest.dicRequest.put("TrxAmount", object.getString("AAE019")); //退货金额 （必要信息）
		tRequest.dicRequest.put("MerchantRemarks", ""); //附言
		// 根据商户号获取商户所在的properties文件中的索引
		PropertiesUtil proUtil = new PropertiesUtil();
		int aae051Index = proUtil.getabcAAE051(object.getString("AAE051")); // 商户号
		// 传送退款请求并取得退货结果
		JSON json = tRequest.extendPostRequest(aae051Index);
		System.out.println("农行退货返回：ReturnCode:"+json.GetKeyValue("ReturnCode")+"-------ErrorMessage:"+json.GetKeyValue("ErrorMessage"));
		if(json.GetKeyValue("ReturnCode").equals("0000")) {
//			updOrderAAE356(object, true);
			datas.put("AAE014", "");//清算日期HostDate
			datas.put("AAE015", json.GetKeyValue("iRspRef"));	//银行返回交易流水号iRspRef
			datas.put("AAE016","NHTK");	//交易缩写
			datas.put("AAE017","");	//商户日期时间
			datas.put("AAE356","1");
			datas.put("AAE013", "");
			context.getDatas().put("MSG", datas);
		} else {
//			updOrderAAE356(object, false);
			datas.put("AAE014", "");//清算日期HostDate
			datas.put("AAE015", "");	//银行返回交易流水号iRspRef
			datas.put("AAE016","NHTK");	//交易缩写
			datas.put("AAE017","");	//商户日期时间
			datas.put("AAE356","2");
			datas.put("AAE013", "失败");
			context.getDatas().put("MSG", datas);
		}
	}
	
	/**
	 * 建行退款
	 * @param object
	 * @param sign
	 */
	public void jhRefund(JSONObject object) {
		Map<String, String> reqMap = new HashMap<String, String>();
		reqMap.put("version", PayConf.PAY_VERSION);
		reqMap.put("charset", PayConf.CHARSET);
		reqMap.put("signMethod", PayConf.SIGNMETHOD);
		reqMap.put("transType", PayConf.REF_TRANSTYPE);
		reqMap.put("merId", object.getString("AAE051")); // 商户号
		reqMap.put("backEndUrl", PayConf.REFUND_BACKEND_URL); // 异步返回地址
		reqMap.put("orderTime", DateUtil.currentTime());
		reqMap.put("orderNumber", object.getString("AAZ288")+"R"); // 订单号
		reqMap.put("qid", object.getString("AAD008")); // 平台交易流水号
		// 建行退款时，将元转为分
		reqMap.put("refAmount", new BigDecimal(object.getString("AAE019")).multiply(new BigDecimal(100)).intValue()+""); // 交易金额
		reqMap.put("orderCurrency", PayConf.ORDERCURRENCY);
		String[] paramKeys = new String[] { "version", "charset", "signMethod",
				"transType", "merId", "backEndUrl", "orderTime", "orderNumber",
				"qid", "refAmount", "orderCurrency"};
		Map<String, String> paramMap = Maps.newHashMap();
		for (String item : paramKeys) {
			paramMap.put(item, reqMap.get(item));
		}

		// 生成加密签名串
		String sign = AppUtils.signBeforePost(paramMap, object.getString("BAE300"), paramMap.get("charset"));
		paramMap.put("sign", sign);
		System.out.println("向清算平台发送退款请求:" + AppUtils.restMapToStr(paramMap));
		String ret = HttpClientUtil.httpPost(PayConf.REFUND_PAY_URL, paramMap, paramMap.get("charset"));
		System.out.println("清算平台同步响应:" + ret);
		// 处理清算平台同步返回结果
		if (StringUtils.isNotBlank(ret)) {
			String[] retArray = ret.split("&");
			Map<String, String> retMap = Maps.newHashMap();
			for (String item : retArray) {
				String[] itemArray = item.split("=");
				retMap.put(itemArray[0], (2 == itemArray.length ? itemArray[1] : StringUtils.EMPTY));
			}
			//签名验证
    		boolean validate = AppUtils.validate(retMap, object.getString("BAE300"), retMap.get("charset"));
    		if (validate) {
				System.out.println("清算平台同步响应签名验证成功");
				String respCode = retMap.get("respCode");
//				String respMsg = retMap.get("respMsg");
				// 此处添加商户业务逻辑
				if ("00".equals(respCode)) {
					datas.put("AAE014", "");//清算日期HostDate
					datas.put("AAE015", retMap.get("refId"));	//银行返回交易流水号refId
					datas.put("AAE016","JHTK");	//交易缩写
					datas.put("AAE017","");	//商户日期时间
					datas.put("AAE356","1");
					datas.put("AAE013", "");
					context.getDatas().put("MSG", datas);
					System.out.println("清算平台退款请求发送成功");
				} else {
//					updOrderAAE356(object, false); // 修改RA22表中订单状态退货失败
					System.out.println("清算平台退款请求发送失败");
					datas.put("AAE014", "");//清算日期HostDate
					datas.put("AAE015", "");	//银行返回交易流水号refId
					datas.put("AAE016","JHTK");	//交易缩写
					datas.put("AAE017","");	//商户日期时间
					datas.put("AAE356","2");
					datas.put("AAE013", "清算平台退款请求发送失败");
					context.getDatas().put("MSG", datas);
				}
			} else {
//				updOrderAAE356(object, false); // 修改RA22表中订单状态退货失败
				System.out.println("清算平台同步响应签名验证失败");
				datas.put("AAE014", "");//清算日期HostDate
				datas.put("AAE015", "");	//银行返回交易流水号refId
				datas.put("AAE016","JHTK");	//交易缩写
				datas.put("AAE017","");	//商户日期时间
				datas.put("AAE356","2");
				datas.put("AAE013", "清算平台同步响应签名验证失败");
				context.getDatas().put("MSG", datas);
			}
		} else {
//			updOrderAAE356(object, false); // 修改RA22表中订单状态退货失败
			System.out.println("清算平台请求退款失败");
			datas.put("AAE014", "");//清算日期HostDate
			datas.put("AAE015", "");	//银行返回交易流水号refId
			datas.put("AAE016","JHTK");	//交易缩写
			datas.put("AAE017","");	//商户日期时间
			datas.put("AAE356","2");
			datas.put("AAE013", "清算平台请求退款失败");
			context.getDatas().put("MSG", datas);
		}
	}
	
	/**
	 * 修改RA22表退货订单状态
	 * @param object
	 * @param sign
	 */
	public void updOrderAAE356(JSONObject object, boolean sign) {
		StringBuffer sql = new StringBuffer("UPDATE RA22 SET ");
		if(sign) {
			sql.append(" AAE356='1'"); // 退货成功
		} else {
			sql.append(" AAE356='2'"); // 退货失败
		}
		sql.append(" WHERE AAZ288='"+object.getString("AAZ288")+"' AND AAZ295='"+object.getString("AAZ295")+"' ");
		if(object.getString("AAZ295").equals("YC")) {
			sql.append(" AND AAZ2881='"+object.getString("AAZ2881")+"'");
		}
		SqlHelper.execute(sql.toString());
	}
	
	/**
	 * 银行退货操作---暂时作废勿删
	 */
//	public void bankRefund() {
//		System.out.println("------退货交易开始------");
//		JSONArray array = JSONArray.parseArray(context.getParam("MSG"));
//		String resStr = "[";
//		for(int i = 0; i < array.size(); i++) {
//			JSONObject object = array.getJSONObject(i);
//			String bankType = object.getString("AAZ295"); // 银行类别
//			boolean sign = true; // 退货成功标识
//			String AAZ288 = object.getString("AAZ288"); // 订单号
//			if(bankType.equals("YC")) {
//				System.out.println("------邮储退货交易开始--------");
//				sign = psbcRefund(object); // 邮储退货
//				System.out.println("------退货订单信息："+object.toString());
//				System.out.println("------退货成功标识："+sign);
//				System.out.println("------邮储退货交易结束--------");
//			} else if(bankType.equals("NH")) {
//				System.out.println("------农行退货交易开始--------");
//				sign = abcRefund(object); // 农行退货
//				System.out.println("------退货订单信息："+object.toString());
//				System.out.println("------退货成功标识："+sign);
//				System.out.println("------农行退货交易结束--------");
//			}
//			resStr += "{\"AAZ288\":\""+AAZ288+"\",\"isPass\":"+sign+",\"AAZ2881\":\""+object.getString("AAZ2881")+"\",\"AAZ295\":\""+bankType+"\"},";
//		}
//		resStr = resStr.substring(0, resStr.length()-1)+"]";
//		System.out.println(com.alibaba.fastjson.JSON.parseArray(resStr));
//		System.out.println("-------------退货交易结束----------------");
//		context.getDatas().put("MSG", com.alibaba.fastjson.JSON.parseArray(resStr));
//	}
	
//	public void refundBackEnd() {
//		HttpServletResponse resp = context.getResponse();
//		HttpServletRequest req = context.getRequest();
//		resp.setStatus(HttpServletResponse.SC_OK);// 响应清算平台通知
//		// 获取通知参数
//		Map<String, String> reqMap = RequestUtils.getReqMap(req);
//		System.out.println("接收到退款异步通知报文:" + reqMap.toString());
//		// 根据商户号获取秘钥
//		String signkey = API.getSignkey(reqMap.get("merId"));
//		//签名验证
//		boolean validate = AppUtils.validate(reqMap, signkey, reqMap.get("charset"));
//		String orderNumber = reqMap.get("orderNumber"); // 订单号
//		if(orderNumber != null && !orderNumber.equals("")) {
//			// 获取订单号，退货订单号去掉最后一位R
//			orderNumber = orderNumber.substring(0, orderNumber.length()-1);
//		}
//		JSONObject object = new JSONObject();
//		object.put("AAZ288", orderNumber);
//		object.put("AAZ295", "JH");
//		if (validate) {
//			// 签名验证通过
//			if ("1".equals(reqMap.get("state"))) {
//				// 订单退款成功
//				System.out.println("订单退款成功.");
//				updOrderAAE356(object, true);
//				context.getDatas().put("isPass", true);
//			} else if ("2".equals(reqMap.get("state"))) {
//				// 订单退款失败
//				System.out.println("订单退款失败.");
//				updOrderAAE356(object, false);
//				context.getDatas().put("isPass", false);
//			}
//		} else {
//			// 签名验证失败
//			System.out.println("签名验证失败.");
//			updOrderAAE356(object, false);
//			context.getDatas().put("isPass", false);
//		}
//	}
	
	public static void main(String[] args) {
		
		//农行退费
//		RefundRequest tRequest = new RefundRequest();
//		tRequest.dicRequest.put("OrderDate", new SimpleDateFormat("yyyy/MM/dd").format(new Date()));  //订单日期（必要信息）
//		tRequest.dicRequest.put("OrderTime", new SimpleDateFormat("hh:mm:ss").format(new Date())); //订单时间（必要信息）
//		tRequest.dicRequest.put("MerRefundAccountNo", "");  //商户退款账号
//		tRequest.dicRequest.put("MerRefundAccountName", ""); //商户退款名
//		tRequest.dicRequest.put("OrderNo", "49483046"); //原交易编号（必要信息）
//		tRequest.dicRequest.put("NewOrderNo", "49483046"+"R"); //交易编号（必要信息）
//		tRequest.dicRequest.put("CurrencyCode", PayConf.ORDERCURRENCY); //交易币种（必要信息）
//		tRequest.dicRequest.put("TrxAmount", "200"); //退货金额 （必要信息）
//		tRequest.dicRequest.put("MerchantRemarks", ""); //附言
//		// 根据商户号获取商户所在的properties文件中的索引
//		PropertiesUtil proUtil = new PropertiesUtil();
//		int aae051Index = proUtil.getabcAAE051("103882630000083"); // 商户号
//		// 传送退款请求并取得退货结果
//		JSON json = tRequest.extendPostRequest(aae051Index);
//		System.out.println(json);
//		System.out.println("农行退货返回：ReturnCode:"+json.GetKeyValue("ReturnCode")+"-------ErrorMessage:"+json.GetKeyValue("ErrorMessage"));
		
		
		//建行退费
		
		Map<String, String> reqMap = new HashMap<String, String>();
		reqMap.put("version", PayConf.PAY_VERSION);
		reqMap.put("charset", PayConf.CHARSET);
		reqMap.put("signMethod", PayConf.SIGNMETHOD);
		reqMap.put("transType", PayConf.REF_TRANSTYPE);
		reqMap.put("merId", "41844"); // 商户号
		reqMap.put("backEndUrl", PayConf.REFUND_BACKEND_URL); // 异步返回地址
		reqMap.put("orderTime", DateUtil.currentTime());
		reqMap.put("orderNumber", "49673504"+"R"); // 订单号
		reqMap.put("qid", "J151810926720170412103254228"); // 平台交易流水号
		// 建行退款时，将元转为分
		reqMap.put("refAmount", new BigDecimal("300").multiply(new BigDecimal(100)).intValue()+""); // 交易金额
		reqMap.put("orderCurrency", PayConf.ORDERCURRENCY);
		String[] paramKeys = new String[] { "version", "charset", "signMethod",
				"transType", "merId", "backEndUrl", "orderTime", "orderNumber",
				"qid", "refAmount", "orderCurrency"};
		Map<String, String> paramMap = Maps.newHashMap();
		for (String item : paramKeys) {
			paramMap.put(item, reqMap.get(item));
		}

		// 生成加密签名串
		String sign = AppUtils.signBeforePost(paramMap, "6LYGFNY7ULPR3DQDN7S9HATIN79KHNJM8Z1S45WLMWJFEKWJXTX9KG6W95D2", paramMap.get("charset"));//密钥
		paramMap.put("sign", sign);
		System.out.println("向清算平台发送退款请求:" + AppUtils.restMapToStr(paramMap));
		String ret = HttpClientUtil.httpPost(PayConf.REFUND_PAY_URL, paramMap, paramMap.get("charset"));
		System.out.println("清算平台同步响应:" + ret);
		// 处理清算平台同步返回结果
		if (StringUtils.isNotBlank(ret)) {
			String[] retArray = ret.split("&");
			Map<String, String> retMap = Maps.newHashMap();
			for (String item : retArray) {
				String[] itemArray = item.split("=");
				retMap.put(itemArray[0], (2 == itemArray.length ? itemArray[1] : StringUtils.EMPTY));
			}
			//签名验证
    		boolean validate = AppUtils.validate(retMap, "7ZL69WZ5E1MQJ3TB5SPEZFD6H28ZGNPNDIXQC19AXYP9L65GN78MB1195IUT", retMap.get("charset"));
    		if (validate) {
				System.out.println("清算平台同步响应签名验证成功");
				String respCode = retMap.get("respCode");
//				String respMsg = retMap.get("respMsg");
				// 此处添加商户业务逻辑
				if ("00".equals(respCode)) {
					System.out.println("清算平台退款请求发送成功");
				} else {
//					updOrderAAE356(object, false); // 修改RA22表中订单状态退货失败
					System.out.println("清算平台退款请求发送失败");
				}
			} else {
//				updOrderAAE356(object, false); // 修改RA22表中订单状态退货失败
				System.out.println("清算平台同步响应签名验证失败");
			}
		} else {
//			updOrderAAE356(object, false); // 修改RA22表中订单状态退货失败
			System.out.println("清算平台请求退款失败");
		}
	}
}
